//
//  main.m
//  XOR-Encrypt
//
//  Created by apple on 2019/12/2.
//  Copyright © 2019 apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#include <CommonCrypto/CommonDigest.h>

// 加密使用的key
#define kChannelID @"321"

// 加密处理后，文件命名的前缀 后缀
#define kFilePrefix @"fw_"
#define kFileSuffix @""

// 需要处理的资源文件夹路径
#define kResFolderPath @"/Users/apple/Desktop/XOR-Encrypt/Res"

/// MD5加密
NSString* md5(NSString *text) {
    const char *cStr = [text UTF8String];
    unsigned char result[16];
    
    CC_MD5(cStr, (unsigned char)strlen(cStr), result );
    NSString *md5Str = [NSString stringWithFormat:
                        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                        result[0], result[1], result[2], result[3],
                        result[4], result[5], result[6], result[7],
                        result[8], result[9], result[10], result[11],
                        result[12], result[13], result[14], result[15]
                        ];
    return md5Str;
}

/// 异或加密（XOR）--文本、图片、音视频
NSData* xor_Encrypt(NSData *sourceData, NSString *secretKey){
    // 获取key的长度
    NSInteger length = secretKey.length;
    // 将OC字符串转换为C字符串
    const char *keys = [secretKey cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cKey[length];
    //memcpy函数的功能是从源内存地址的起始位置开始拷贝若干个字节到目标内存地址中
    memcpy(cKey, keys, length);
    // 数据初始化，空间未分配 配合使用 appendBytes
    NSMutableData *encryptData = [[NSMutableData alloc] initWithCapacity:length];
    // 获取字节指针
    const Byte *point = sourceData.bytes;
    for (int i = 0; i < sourceData.length; i++) {
        // 算出当前位置字节，要和密钥的异或运算的密钥字节
        int l = i % length;
        char c = cKey[l];
        // 异或运算
        Byte b = (Byte) ((point[i]) ^ c);
        // 追加字节
        [encryptData appendBytes:&b length:1];
    }
    return encryptData.copy;
}


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        
        // 加密Key
        NSString *secretKey = md5(kChannelID);
        
        // 获取文件夹下的所以文件放入数组中
        NSArray *shortPicNameArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:kResFolderPath error:nil];
        NSLog(@"shortPicNameArray = %@",shortPicNameArray);
        
        for (NSString *shortPicName in shortPicNameArray) {
            // 截取原文件,名称处理
            NSRange range = [shortPicName rangeOfString:@"."];
            //NSLog(@"range.location = %ld,   range.length = %ld",range.location,range.length);
            
            // 原文件名
            NSString *tempShortPicName = [shortPicName substringToIndex:range.location];
            //NSLog(@"tempShortPicName = %@",tempShortPicName);
            
            // 原文件后缀名
            NSString *tempShortPicSufName = [shortPicName substringFromIndex:range.location];
            //NSLog(@"tempShortPicSufName = %@",tempShortPicSufName);
            // 跳过 .DS_Store 文件的加密
            if ([tempShortPicSufName isEqualToString:@".DS_Store"]) {
                continue;
            }
            
            // 读取文件路径
            NSString *fullPicPath = [kResFolderPath stringByAppendingPathComponent:shortPicName];
            //NSLog(@"fullPicPath = %@",fullPicPath);
            
            // 读取原始数据
            NSData *fullPicData = [NSData dataWithContentsOfFile:fullPicPath];
            //NSLog(@"fullPicData = %@",fullPicData);
            
            // 对数据进行XOR加密
            NSData *encodeFullPicData = xor_Encrypt(fullPicData, secretKey);
            
            // 判断是否制定特定后缀名，若未指定，则用原文件后缀名
            NSString *newShortPicName;
            if (kFileSuffix.length > 0) {
                newShortPicName = [NSString stringWithFormat:@"%@%@%@",kFilePrefix,tempShortPicName,kFileSuffix];
            }else{
                newShortPicName = [NSString stringWithFormat:@"%@%@%@",kFilePrefix,tempShortPicName,tempShortPicSufName];
            }
            
            // 新建新的文件路径
            NSString *newFullPicPath = [kResFolderPath stringByAppendingPathComponent:newShortPicName];
            //NSLog(@"newfullPicPath: %@",newFullPicPath);
            
            // 写入加密后的数据
            [encodeFullPicData writeToFile:newFullPicPath atomically:YES];
        }
    }
    return 0;
}
